/*
 * @描述: 消息通知页面逻辑
 * @版权所有: 广东国星科技有限公司
 * @商业授权: www.mscodecloud.com
 */
import React, { PureComponent, Fragment } from 'react';
import { formatMessage, FormattedMessage } from 'umi-plugin-react/locale';
import { connect } from 'dva';
import moment from 'moment';
import { Row, Col, Card, Form, Input, Select, Tooltip, Icon, Button, DatePicker, Modal, message, Divider, Radio, Popconfirm } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import ProTable from '@ant-design/pro-table';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';

import styles from './Admin.less';

const FormItem = Form.Item;
const { Option } = Select;
const RadioGroup = Radio.Group;
const InputGroup = Input.Group;
const { RangePicker } = DatePicker;
const getValue = obj => Object.keys(obj).map(key => obj[key]).join(',');

const toolbarOptions = [
  [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
  [{ 'font': [] }],
  ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
  ['blockquote', 'code-block'],
  [{ 'header': 1 }, { 'header': 2 }],               // custom button values
  [{ 'list': 'ordered' }, { 'list': 'bullet' }],
  [{ 'script': 'sub' }, { 'script': 'super' }],      // superscript/subscript
  [{ 'indent': '-1' }, { 'indent': '+1' }],          // outdent/indent
  [{ 'direction': 'rtl' }],                         // text direction
  [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
  [{ 'align': [] }],
  ['link', 'image', 'video'],
  ['clean']                                         // remove formatting button
];

const reactQuillOptions = {
  modules: {
    toolbar: toolbarOptions
  }
};

function disabledDate(current) {
  // Can not select days before today 
  return current < moment().startOf('day');
}

const CreateForm = Form.create()(props => {
  const { modalVisible, form, handleAdd, handleModalVisible, typeData, priorityData, usernameData } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      document.querySelector(".ql-editor").innerHTML = '';
      handleAdd(fieldsValue);
    });
  };

  const handleChange = value => {
    form.setFieldsValue({
      'content': value
    })
  };

  return (
    <Modal
      destroyOnClose
      title={formatMessage({ id: 'app.notification.add-notification' })}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
      width='60%'
    >
      <FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 19 }} label={formatMessage({ id: 'app.notification.title' })}>
        {form.getFieldDecorator('title', {
          rules: [
            {
              required: true,
              message: formatMessage({ id: 'validation.title.required' })
            },
            {
              message: formatMessage({ id: 'validation.title.length' }),
              max: 100
            }
          ]
        })(<Input placeholder={formatMessage({ id: 'app.common.enter' })} />)}
      </FormItem>
      <FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 19 }} label={formatMessage({ id: 'app.notification.type' })}>
        {form.getFieldDecorator('type', {
          rules: [
            {
              required: true,
              message: formatMessage({ id: 'validation.type.required' })
            }
          ]
        })(<Select placeholder={formatMessage({ id: 'app.common.choose' })} style={{ width: '100%' }}>
          {typeData && typeData.map(d => (
            <Option key={d.value}>{d.name}</Option>
          ))}
        </Select>)}
      </FormItem>
      <FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 19 }} label={formatMessage({ id: 'app.notification.priority' })}>
        {form.getFieldDecorator('priority', {

        })(<Select placeholder={formatMessage({ id: 'app.common.choose' })} style={{ width: '100%' }}>
          {priorityData && priorityData.map(d => (
            <Option key={d.value}>{d.name}</Option>
          ))}
        </Select>)}
      </FormItem>
      <FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 19 }}
        label={
          <span>
            <FormattedMessage id="app.notification.period" />
            <Tooltip title={<FormattedMessage id="app.notification.period-tooltip" />}>
              <Icon type="info-circle-o" />
            </Tooltip>
          </span>
        }>
        {form.getFieldDecorator('rangeTime', {

        })(<RangePicker
          disabledDate={disabledDate}
          showTime={{
            hideDisabledOptions: true,
            defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
          }}
          format="YYYY-MM-DD HH:mm:ss"
          style={{ width: '100%' }}
        />)}
      </FormItem>
      <FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 19 }} label={formatMessage({ id: 'app.notification.content' })}>
        {form.getFieldDecorator('content', {
          rules: [
            {
              required: true,
              message: formatMessage({ id: 'validation.content.required' })
            }
          ],
          initialValue: ''
        })(<Card bodyStyle={{ padding: 0, margin: 0 }} bordered={false}>
          <ReactQuill {...reactQuillOptions} onChange={handleChange} />
        </Card>)}
      </FormItem>
      <FormItem labelCol={{ span: 3 }} wrapperCol={{ span: 19 }}
        label={
          <span>
            <FormattedMessage id="app.notification.publish-object" />
            <Tooltip title={<FormattedMessage id="app.notification.choose-tooltip" />}>
              <Icon type="info-circle-o" />
            </Tooltip>
          </span>
        }>
        {form.getFieldDecorator('username', {

        })(<Select placeholder={formatMessage({ id: 'app.common.choose' })} style={{ width: '100%' }} showSearch optionFilterProp="children" mode="multiple">
          {usernameData && usernameData.map(d => (
            <Option key={d.value}>{d.value}</Option>
          ))}
        </Select>)}
      </FormItem>
    </Modal>
  );
});

@Form.create()
class UpdateForm extends PureComponent {
  static defaultProps = {
    handleUpdate: () => { },
    handleUpdateModalVisible: () => { },
    values: {}
  };

  constructor(props) {
    super(props);

    this.state = {
      formVals: {
        title: props.values.title,
        content: props.values.content,
        type: props.values.type,
        priority: props.values.priority,
        rangeTime: props.values.startTime && props.values.endTime ? [moment(props.values.startTime), moment(props.values.endTime)] : [],
        username: props.values.username,
        id: props.values.id
      }
    };

    this.formLayout = {
      labelCol: { span: 3 },
      wrapperCol: { span: 19 }
    };
  }

  renderContent = (formVals) => {
    const { form, typeData, priorityData, usernameData } = this.props;
    const handleChange = value => {
      form.setFieldsValue({
        'content': value
      })
    };

    return [
      <FormItem key="title" {...this.formLayout} label={formatMessage({ id: 'app.notification.title' })}>
        {form.getFieldDecorator('title', {
          rules: [
            {
              required: true,
              message: formatMessage({ id: 'validation.title.required' })
            },
            {
              message: formatMessage({ id: 'validation.title.length' }),
              max: 100
            }
          ],
          initialValue: formVals.title
        })(<Input placeholder={formatMessage({ id: 'app.common.enter' })} />)}
      </FormItem>,
      <FormItem key="type" {...this.formLayout} label={formatMessage({ id: 'app.notification.type' })}>
        {form.getFieldDecorator('type', {
          rules: [
            {
              required: true,
              message: formatMessage({ id: 'validation.type.required' })
            }
          ],
          initialValue: formVals.type
        })(<Select placeholder={formatMessage({ id: 'app.common.choose' })} style={{ width: '100%' }}>
          {typeData && typeData.map(d => (
            <Option key={d.value}>{d.name}</Option>
          ))}
        </Select>)}
      </FormItem>,
      <FormItem key="priority" {...this.formLayout} label={formatMessage({ id: 'app.notification.priority' })}>
        {form.getFieldDecorator('priority', {
          initialValue: formVals.priority
        })(<Select placeholder={formatMessage({ id: 'app.common.choose' })} style={{ width: '100%' }}>
          {priorityData && priorityData.map(d => (
            <Option key={d.value}>{d.name}</Option>
          ))}
        </Select>)}
      </FormItem>,
      <FormItem key="rangeTime" {...this.formLayout}
        label={
          <span>
            <FormattedMessage id="app.notification.period" />
            <Tooltip title={<FormattedMessage id="app.notification.period-tooltip" />}>
              <Icon type="info-circle-o" />
            </Tooltip>
          </span>
        }>
        {form.getFieldDecorator('rangeTime', {
          initialValue: formVals.rangeTime
        })(<RangePicker
          disabledDate={disabledDate}
          showTime={{
            hideDisabledOptions: true,
            defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')],
          }}
          format="YYYY-MM-DD HH:mm:ss"
          style={{ width: '100%' }}
        />)}
      </FormItem>,
      <FormItem key="content" {...this.formLayout} label={formatMessage({ id: 'app.notification.content' })}>
        {form.getFieldDecorator('content', {
          rules: [
            {
              required: true,
              message: formatMessage({ id: 'validation.content.required' })
            }
          ],
          initialValue: formVals.content
        })(<Card bodyStyle={{ padding: 0, margin: 0 }} bordered={false}>
          <ReactQuill {...reactQuillOptions} onChange={handleChange} defaultValue={formVals.content} />
        </Card>)}
      </FormItem>,
      <FormItem key="username" {...this.formLayout}
        label={
          <span>
            <FormattedMessage id="app.notification.publish-object" />
            <Tooltip title={<FormattedMessage id="app.notification.choose-tooltip" />}>
              <Icon type="info-circle-o" />
            </Tooltip>
          </span>
        }>
        {form.getFieldDecorator('username', {
          initialValue: formVals.username
        })(<Select placeholder={formatMessage({ id: 'app.common.choose' })} style={{ width: '100%' }} showSearch optionFilterProp="children" mode="multiple">
          {usernameData && usernameData.map(d => (
            <Option key={d.value}>{d.value}</Option>
          ))}
        </Select>)}
      </FormItem>
    ];
  };

  render() {
    const { updateModalVisible, handleUpdateModalVisible, values } = this.props;
    const { formVals } = this.state;
    const okUpdateHandle = () => {
      const { form, handleUpdate } = this.props;
      const { formVals: oldValue } = this.state;
      form.validateFields((err, fieldsValue) => {
        if (err) return;
        const formVals = { ...oldValue, ...fieldsValue };
        this.setState(
          {
            formVals
          },
          () => {
            handleUpdate(formVals);
          }
        );
      });
    };

    return (
      <Modal
        destroyOnClose
        title={formatMessage({ id: 'app.notification.edit-notification' })}
        visible={updateModalVisible}
        onOk={okUpdateHandle}
        onCancel={() => handleUpdateModalVisible(false, values)}
        afterClose={() => handleUpdateModalVisible()}
        width='60%'
      >
        {this.renderContent(formVals)}
      </Modal>
    );
  }
}

/* eslint react/no-multi-comp:0 */
@connect(({ notification, sysUser, user, loading }) => ({
  notification,
  sysUser,
  currentUser: user.currentUser,
  loading: loading.models.notification
}))
@Form.create()
class Notification extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    selectedRows: [],
    formValues: {},
    updateFormValues: {},
    typeData: {},
    priorityData: {},
    usernameData: {},
    hiddenMenuButton: localStorage.getItem('mscode_menubutton')
  };

  columns = [
    {
      title: formatMessage({ id: 'app.notification.title' }),
      copyable: true,
      ellipsis: true,
      dataIndex: 'title'
    },
    {
      title: formatMessage({ id: 'app.notification.type' }),
      dataIndex: 'typeCn'
    },
    {
      title: formatMessage({ id: 'app.notification.priority' }),
      dataIndex: 'priorityCn'
    },
    {
      title: formatMessage({ id: 'app.notification.publisher' }),
      dataIndex: 'publisher'
    },
    {
      title: formatMessage({ id: 'app.notification.create-time' }),
      dataIndex: 'createTime',
      sorter: true,
      render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>
    },
    {
      title: formatMessage({ id: 'app.common.operate' }),
      align: 'center',
      render: (text, record) => (
        <Fragment>
          {this.state.hiddenMenuButton.indexOf('notification:update') !== -1 ? null :
            <a onClick={() => this.handleUpdateModalVisible(true, record)}><Icon type="edit" />{formatMessage({ id: 'app.common.edit' })}</a>
          }
          <Divider type="vertical" />
          <Popconfirm title={formatMessage({ id: 'app.common.confirm-delete' })} onConfirm={() => this.deleteItem(record.id)}>
            {this.state.hiddenMenuButton.indexOf('notification:delete') !== -1 ? null :
              <a><Icon type="delete" />{formatMessage({ id: 'app.common.delete' })}</a>
            }
          </Popconfirm>
        </Fragment>
      )
    }
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'notification/fetch'
    });
    dispatch({
      type: 'notification/fetchType'
    });
    dispatch({
      type: 'notification/fetchPriority'
    });
    dispatch({
      type: 'sysUser/fetchUsername'
    });
  }

  handleBasicTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'notification/fetch',
      payload: params
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {}
    });
    dispatch({
      type: 'notification/fetch',
      payload: {}
    });
  };

  deleteItem = id => {
    const { dispatch } = this.props;
    dispatch({
      type: 'notification/delete',
      payload: {
        id: id
      }
    }).then(response => {
      if (response.message == 'success') {
        this.setState({
          selectedRows: []
        });
        message.success(formatMessage({ id: 'app.common.delete-success' }));
      } else {
        message.warning(response.message);
      }
      dispatch({
        type: 'notification/fetch',
        payload: {}
      });
    });
  }

  handleDeleteClick = () => {
    const { selectedRows } = this.state;

    if (selectedRows.length === 0) {
      message.warning(formatMessage({ id: 'app.common.choose-delete' }));
      return;
    }

    Modal.confirm({
      title: formatMessage({ id: 'app.common.batch-delete' }),
      content: formatMessage({ id: 'app.common.confirm-batch-delete' }),
      okText: formatMessage({ id: 'app.common.confirm' }),
      cancelText: formatMessage({ id: 'app.common.cancel' }),
      onOk: () => this.deleteItem(selectedRows.map(row => row.id)),
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows
    });
  };

  handleSearch = e => {
    if (e) {
      e.preventDefault();
    }
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue
      };
      this.setState({
        formValues: values
      });
      dispatch({
        type: 'notification/fetch',
        payload: values
      });
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag
    });
  };

  handleUpdateModalVisible = (flag, record) => {
    this.setState({
      updateModalVisible: !!flag,
      updateFormValues: record || {}
    });
  };

  handleAdd = fields => {
    const { dispatch, currentUser } = this.props;
    dispatch({
      type: 'notification/add',
      payload: {
        body: {
          title: fields.title,
          content: fields.content,
          type: fields.type,
          priority: fields.priority,
          publisher: currentUser.username,
          startTime: fields.rangeTime ? fields.rangeTime[0] : null,
          endTime: fields.rangeTime ? fields.rangeTime[1] : null
        },
        expand: {
          username: fields.username ? fields.username.toString() : null
        }
      }
    }).then(response => {
      if (response.message == 'success') {
        message.success(formatMessage({ id: 'app.common.add-success' }));
        this.handleModalVisible();
      } else {
        message.warning(response.message);
      }
      dispatch({
        type: 'notification/fetch',
        payload: {}
      });
    });
  };

  handleUpdate = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'notification/update',
      payload: {
        body: {
          title: fields.title,
          content: fields.content,
          type: fields.type,
          priority: fields.priority,
          startTime: fields.rangeTime ? fields.rangeTime[0] : null,
          endTime: fields.rangeTime ? fields.rangeTime[1] : null,
          id: fields.id
        },
        expand: {
          username: fields.username ? fields.username.toString() : null
        }
      }
    }).then(response => {
      if (response.message == 'success') {
        message.success(formatMessage({ id: 'app.common.edit-success' }));
        this.handleUpdateModalVisible();
      } else {
        message.warning(response.message);
      }
      dispatch({
        type: 'notification/fetch',
        payload: {}
      });
    });
  };

  renderSimpleForm() {
    const { form: { getFieldDecorator }, notification: { typeSelectData } } = this.props;
    let typeData;
    if ({ typeSelectData }.typeSelectData) {
      typeData = { typeSelectData }.typeSelectData;
    }
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label={formatMessage({ id: 'app.notification.title' })}>
              {getFieldDecorator('title')(<Input placeholder={formatMessage({ id: 'app.common.enter' })} />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label={formatMessage({ id: 'app.notification.content' })}>
              {getFieldDecorator('content')(<Input placeholder={formatMessage({ id: 'app.common.enter' })} />)}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label={formatMessage({ id: 'app.notification.type' })}>
              {getFieldDecorator('type')(
                <Select placeholder={formatMessage({ id: 'app.common.choose' })} style={{ width: '100%' }}>
                  {typeData && typeData.map(d => (
                    <Option key={d.value}>{d.name}</Option>
                  ))}
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit" icon="search">
                {formatMessage({ id: 'app.common.query' })}
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset} type="primary" icon="reload">
                {formatMessage({ id: 'app.common.reset' })}
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const { notification: { data, typeSelectData, prioritySelectData }, sysUser: { usernameSelectData }, loading } = this.props;
    const { /**selectedRows,**/ modalVisible, updateModalVisible, updateFormValues } = this.state;
    let typeData;
    let priorityData;
    let usernameData;
    if ({ typeSelectData }.typeSelectData) {
      typeData = { typeSelectData }.typeSelectData;
    }
    if ({ prioritySelectData }.prioritySelectData) {
      priorityData = { prioritySelectData }.prioritySelectData;
    }
    if ({ usernameSelectData }.usernameSelectData) {
      usernameData = { usernameSelectData }.usernameSelectData;
    }
    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible
    };
    const updateMethods = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate
    };
    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        this.handleSelectRows(selectedRows);
      }
    };
    return (
      <PageHeaderWrapper content={formatMessage({ id: 'app.notification.notification' })}>
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              {this.state.hiddenMenuButton.indexOf('notification:add') !== -1 ? null :
                <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                  {formatMessage({ id: 'app.common.add' })}
                </Button>
              }
              {this.state.hiddenMenuButton.indexOf('notification:delete') !== -1 ? null :
                <Button icon="delete" type="danger" ghost onClick={this.handleDeleteClick}>
                  {formatMessage({ id: 'app.common.batch-delete' })}
                </Button>
              }
            </div>
            <ProTable
              bordered={true}
              search={false}
              rowKey={record => record.id}
              rowSelection={rowSelection}
              loading={loading}
              dataSource={data ? data.list : []}
              pagination={data ? data.pagination : {}}
              columns={this.columns}
              onChange={this.handleBasicTableChange}
              options={{
                density: true,
                reload: () => {
                  this.handleSearch();
                },
                fullScreen: true,
                setting: true,
              }}
            />
          </div>
        </Card>
        <CreateForm {...parentMethods} modalVisible={modalVisible} typeData={typeData} priorityData={priorityData} usernameData={usernameData} />
        {updateFormValues && Object.keys(updateFormValues).length ? (
          <UpdateForm
            {...updateMethods}
            updateModalVisible={updateModalVisible}
            values={updateFormValues}
            typeData={typeData}
            priorityData={priorityData}
            usernameData={usernameData}
          />
        ) : null}
      </PageHeaderWrapper>
    );
  }
}

export default Notification;
